package com.sc.controller;

import com.github.pagehelper.PageInfo;
import com.sc.pojo.StudyClassify;
import com.sc.pojo.StudyFile;
import com.sc.pojo.StudyNote;
import com.sc.pojo.User;
import com.sc.service.StudyClassifyService;
import com.sc.service.StudyFileService;
import com.sc.service.StudyNoteService;
import com.sc.util.UploadDownloadUtil;
import org.apache.maven.model.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.jws.WebParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/study")
public class StudyController {
    @Autowired
    StudyFileService ss;
    @Autowired
    StudyClassifyService scf;
    @Autowired
    StudyNoteService sn;
    @RequestMapping("/toCase")
    public String toCase() {
        return "/study/case";
    }

    @RequestMapping("/show")
    public String show(@RequestParam(defaultValue = "1") Integer pageNum, Map m, HttpSession session,String fname) {
        if(fname==null){
            PageInfo<StudyFile> p = ss.show(pageNum,4);
            m.put("p", p);
        }else {
            PageInfo<StudyFile> p = ss.showByfname(pageNum, 4,fname);
            m.put("p", p);
        }


        if (fname!=null){
            m.put("fname",fname);
        }
        List<StudyClassify> list = scf.queryAll();
        session.setAttribute("list", list);
        return "/study/list";
    }
    @RequestMapping("/addNote")
    public String addNote(HttpSession session, StudyNote note,MultipartFile fileName, HttpServletRequest req ) throws IOException {
        StudyFile file=new StudyFile();
        User user=(User)session.getAttribute("theUser");
        if(fileName.getOriginalFilename().length()>0){
            String oldName=fileName.getOriginalFilename();
            String newName = UploadDownloadUtil.upload(req, fileName);
            file.setFname(oldName);
            file.setCfile(newName);
            file.setId(user.getId());
        }
        note.setId(user.getId());
        sn.aadNote(note,file);
        return "redirect:/study/show";
    }
    @RequestMapping("/shareNote")
    public String shreNote(Integer nid){
        StudyNote note=sn.getStudyNoteByNid(nid);
        note.setShare("0");
        sn.updateStudyNote(note);
        return "redirect:/study/share";
    }
    @RequestMapping("/deleteNote")
    public String deleteNote(Integer nid,Integer fid) {
        //文件表删除
        ss.deleteStudyFile(fid);
        //笔记表删除
        sn.deleteStudyNote(nid);
        return "/study/list";

    }
}
